//
//  TitleScrollView.m
//  xinyiheziTest
//
//  Created by 袁飞霞 on 16/5/9.
//  Copyright © 2016年 cn.sophietobeabetterone. All rights reserved.
//

#import "TitleView.h"
@interface TitleView()
@property(nonatomic,strong)NSMutableArray *buttons;
@property (nonatomic, weak) UIButton *selectedBtn;
@property (nonatomic, weak) UIView *redView;
@end
@implementation TitleView


-(instancetype)initTitleViewWithTitles:(NSArray *)titles{

    if (self = [super init])
    {
        int index = (int)titles.count;
        for (int i = 0; i < index; ++i) {
            UIButton *btn = [[UIButton alloc]init];
            
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
            btn.tag = i;
            [btn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
            [self.buttons addObject:btn];
            [btn setTitle:titles[i] forState:UIControlStateNormal];
            [self addSubview:btn];
        }
        UIView *redView = [[UIView alloc]init];
        redView.backgroundColor = [UIColor redColor];
        
        [self addSubview:redView];
        _redView = redView;
    }
    return self;
}
-(void)btnDidClick:(UIButton *)btn
{
    if (btn == self.selectedBtn) {
        return;
    }
    btn.selected = YES;
    self.selectedBtn.selected = NO;
    self.selectedBtn = btn;
    NSLog(@"%ld",(long)btn.tag);
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    CGFloat btnW = screenW/self.buttons.count;
     CGFloat btnH = 21;
   //点击按钮更新红色的frame值 并实现动画效果
   [UIView animateWithDuration:0.2 animations:^{
        self.redView.frame =CGRectMake((btn.tag) * btnW , btnH, btnW, 3);
           }];
}

-(void)layoutSubviews{
    [super layoutSubviews];
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    CGFloat btnW = screenW/self.buttons.count;
    CGFloat btnH = 21;
    CGFloat redViewH = 3;
    CGFloat __block btnX = 0;

   [self.buttons enumerateObjectsUsingBlock:^(UIButton *btn, NSUInteger idx, BOOL * _Nonnull stop) {
         btn.frame = CGRectMake(idx * btnW  , 0, btnW, btnH);
//       btn.frame = CGRectMake(btnX, 0, btn.frame.size.width, btnH);
//       btnX += btn.frame.size.width;
       
    }];
    self.redView.frame = CGRectMake(0, btnH, btnW, redViewH);
}

-(NSMutableArray *)buttons
{
    if (_buttons== nil) {
        _buttons = [[NSMutableArray alloc] init];
    }
    return _buttons;
}
@end
